package com.sky.service.impl;

import cn.hutool.socket.SocketUtil;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yangeit
 * @date 2023年11月29日 10:47
 * @Description
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;
    @Override
    public TurnoverReportVO getTurnnover(LocalDate begin, LocalDate end) {
//        1. 获得x轴的数据 日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
         ArrayList<LocalDate> dateList = new ArrayList<>();
         //添加第一天
        dateList.add(begin);

//        循环增加天数
        while (!begin.equals(end)){
            begin = begin.plusDays(1);//10-3
            dateList.add(begin);
        }
        log.info("x轴，日期：{}",dateList);

//       2. 获得y轴的数据，营业额，以逗号分隔，例如：406.0,1520.0,75.0
        ArrayList<Double> turnoverList = new ArrayList<>();

        for (LocalDate date : dateList) {

//            获得每天的营业额（零时-23:59：59秒)
             LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
             LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

//             为了方便查询，将3个参数封装一下
            final HashMap map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);

         Double turnover=orderMapper.getTurnnoverByCondition(map);

         turnover=turnover==null?0.0:turnover;

            turnoverList.add(turnover);
        }

        log.info("y轴，转换前：营业额：{}",turnoverList);


        String turnoverListStr = StringUtils.join(turnoverList, ",");
        String dateListStr = StringUtils.join(dateList, ",");
//        log.info("y轴，转换后：营业额：{}",turnoverListStr);


        TurnoverReportVO build = TurnoverReportVO.builder().turnoverList(turnoverListStr).dateList(dateListStr).build();
        return build;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

//        1.日期
        //        1. 获得x轴的数据 日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        ArrayList<LocalDate> dateList = new ArrayList<>();
        //添加第一天
        dateList.add(begin);

//        循环增加天数
        while (!begin.equals(end)){
            begin = begin.plusDays(1);//10-3
            dateList.add(begin);
        }
        log.info("x轴，日期：{}",dateList);

//        2.用户总量
        ArrayList<Integer> totalUserCountList = new ArrayList<>();
//        3. 今日新增用户
        ArrayList<Integer> newUserCountList = new ArrayList<>();


        for (LocalDate date : dateList) {

//            获得每天的营业额（零时-23:59：59秒)
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
// select count(*) from user where create_time >= beginTime and create_time<= endTime
          Integer newUserCount=  userMapper.getUserCountByCondition(beginTime,endTime);


// select count(*) from user where  create_time<= endTime
          Integer totalUserCount=  userMapper.getUserCountByCondition(null,endTime);
            totalUserCountList.add(totalUserCount);
            newUserCountList.add(newUserCount);

        }

         UserReportVO build = UserReportVO.builder()
                 .dateList(StringUtils.join(dateList,","))
                 .newUserList(StringUtils.join(newUserCountList,","))
                 .totalUserList(StringUtils.join(totalUserCountList,","))
                 .build();

        return build;
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //        1.日期
        //        1. 获得x轴的数据 日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        ArrayList<LocalDate> dateList = new ArrayList<>();
        //添加第一天
        dateList.add(begin);

//        循环增加天数
        while (!begin.equals(end)){
            begin = begin.plusDays(1);//10-3
            dateList.add(begin);
        }
        log.info("x轴，日期：{}",dateList);

//        2.每日总订单数
        ArrayList<Integer> orderCountList = new ArrayList<>();
//        3. 每日有效订单数
        ArrayList<Integer> validOrderCountList = new ArrayList<>();


        for (LocalDate date : dateList) {

//            获得每天的订单总数（零时-23:59：59秒)
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

//            订单总数
            Integer orderCount=  orderMapper.getOrderCount(beginTime,endTime,null);

//            有效订单数
            Integer validOrderCount=  orderMapper.getOrderCount(beginTime,endTime,Orders.COMPLETED);


            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);

        }



         Integer orderCount = orderCountList.stream().reduce(Integer::sum).get();
         Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

         Double orderCompletionRate=0.0;
         if (orderCount!=0){
             orderCompletionRate=validOrderCount.doubleValue()/orderCount;

         }


        OrderReportVO build = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(orderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();


        return build;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
//        begin 2023-11-23  00:00:00
//        end   2023-11-29  23:59:59
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

      List<GoodsSalesDTO> list= orderMapper.getSalesTop10(beginTime,endTime);

//      目标1：名字1，名字2，名字3
//      目标2：数量1，数量2，数量3


        
         List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
         List<Integer> numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());


         SalesTop10ReportVO build = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();

        return build;
    }


    @Autowired
    WorkspaceService workspaceService;

    @Override
    public void export(HttpServletResponse response) throws IOException {

        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

//        求取起始和截止时间
        LocalDateTime dateBeginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime dateEndTime = LocalDateTime.of(dateEnd, LocalTime.MAX);

        //求取营业额数据
        BusinessDataVO businessData = workspaceService.getBusinessData(dateBeginTime, dateEndTime);


//        获取模版excel对象
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("运营数据报表模板.xlsx");

        XSSFWorkbook workbook = new XSSFWorkbook(resourceAsStream);
        XSSFSheet sheetAt = workbook.getSheetAt(0);

        //获取第2行，索引为1的row
        sheetAt.getRow(1).getCell(0).setCellValue("时间："+dateBegin+"至"+dateEnd);


        XSSFRow row3 = sheetAt.getRow(3);
        row3.getCell(1).setCellValue(businessData.getTurnover());
        row3.getCell(3).setCellValue(businessData.getOrderCompletionRate());
        row3.getCell(5).setCellValue(businessData.getNewUsers());


        XSSFRow row4 = sheetAt.getRow(4);
        row4.getCell(1).setCellValue(businessData.getValidOrderCount());
        row4.getCell(3).setCellValue(businessData.getUnitPrice());


        //第三部分数据，每日营业数据

        for (int i = 0; i < 30; i++) {
            LocalDate date = dateEnd.minusDays(i);
            LocalDateTime currentdateBeginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime currentdateEndTime = LocalDateTime.of(date, LocalTime.MAX);


            BusinessDataVO businessData1 = workspaceService.getBusinessData(currentdateBeginTime, currentdateEndTime);

            XSSFRow row = sheetAt.getRow(7 + i);

            row.getCell(0).setCellValue(date.toString());
            row.getCell(1).setCellValue(businessData1.getTurnover());
            row.getCell(2).setCellValue(businessData1.getValidOrderCount());
            row.getCell(3).setCellValue(businessData1.getOrderCompletionRate());
            row.getCell(4).setCellValue(businessData1.getUnitPrice());
            row.getCell(5).setCellValue(businessData1.getNewUsers());



        }


        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
        workbook.close();


    }
}
